package pwd.allen.password;

/**
 * 密码验证工具类
 *
 * @author 门那粒沙
 * @create 2021-12-19 22:40
 **/
public class PasswordUtil {

    /**
     * 包含数字
     */
    public static final String REGEX_CONTAIN_DIGIT = ".*\\d.*";
    /**
     * 包含大写字母
     */
    public static final String REGEX_CONTAIN_UPPER_LETTER = ".*[A-Z].*";
    /**
     * 包含小写字母
     */
    public static final String REGEX_CONTAIN_LOWER_LETTER = ".*[a-z].*";
    /**
     * 包含字母
     */
    public static final String REGEX_CONTAIN_LETTER = ".*[A-Za-z].*";
    /**
     * 包含特殊字符
     */
    public static final String REGEX_CONTAIN_SPECIAL = ".*[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？\\\\].*";

    protected String password;

    public PasswordUtil() {
    }
    public PasswordUtil(String password) {
        this.password = password;
    }
    public void setPassword(String password) {
        this.password = password;
    }

    /**
     * 长度不少于n个字符
     * @return
     */
    public boolean lengthLT(int n) {
        int length = password.trim().length();
        return length >= n;
    }

    /**
     * 是否含有数字
     * @return
     */
    public boolean containDigit() {
        return this.password.matches(REGEX_CONTAIN_DIGIT);
    }

    /**
     * 是否含有字母
     * @return
     */
    public boolean containLetter() {
        return this.password.matches(REGEX_CONTAIN_LETTER);
    }

    /**
     * 是否含有特殊字符
     * @return
     */
    public boolean containSpecial() {
        return this.password.matches(REGEX_CONTAIN_SPECIAL);
    }

    /**
     * 验证规则中是否至少有n个通过
     *
     * @param num 要求验证通过的最小规则数
     * @param regexs 要验证的规则
     * @return
     */
    public boolean matchAtLeast(int num, String... regexs) {
        if (num == 0 || regexs == null || regexs.length == 0) {
            return false;
        }
        int int_match = 0;
        for (String regex : regexs) {
            if (password.matches(regex)) {
                int_match++;
            }
        }
        if (int_match >= num) {
            return true;
        }
        return false;
    }

}
